//
//  QCEmotionBottomView.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/10.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

enum QCEmotionBottomViewType: Int{
    case recent = 100
    case normal = 101
    case emoji = 102
    case lxh = 103
}

class QCEmotionBottomView: UIStackView {
  //记录上一次选中的按钮
    var lastButton:UIButton?
    
    //定义一个闭包
    var cloure:((QCEmotionBottomViewType)->())?
    
    //容器视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //布局方式
        axis = .horizontal
        //填充方式
        distribution = .fillEqually
        
        addChildButtons(imgName: "left", title: "最近", type:.recent)
        addChildButtons(imgName: "mid", title: "默认", type: .normal)
        addChildButtons(imgName: "mid", title: "Emoji", type: .emoji)
        addChildButtons(imgName: "right", title: "小浪花", type: .lxh)
    }
    
    //给外界提供一个设置当前按钮状态的方法
    func setupSelectButton(tag: Int){
        
        let button = viewWithTag(tag) as! UIButton
        
        //判断如果与lastButton一样 那么就return
        if  lastButton == button {
            return
        }
        button.isSelected = true
        lastButton?.isSelected = false
        lastButton = button
    }
    
    func buttonClick(button: UIButton){
        
        if lastButton == button {
            return
        }
        
        button.isSelected = true
        lastButton?.isSelected = false
        lastButton = button
        cloure?(QCEmotionBottomViewType(rawValue: button.tag)!)
        
    }
    
    // 创建按钮的公共方法
    func addChildButtons(imgName: String, title: String, type: QCEmotionBottomViewType){
        let button = UIButton()
        // 设置tag
        button.tag = type.rawValue
        if title == "默认" {
            button.isSelected = true
            // 记录
            lastButton = button
        }
        // 监听事件
        button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        button.titleLabel?.font = UIFont.systemFont(ofSize: QCNORMALFONTSIZE)
        button.setTitle(title, for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.selected)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_normal"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"compose_emotion_table_\(imgName)_selected"), for: UIControlState.selected)
        addArrangedSubview(button)
    }

}
